package cn.appsys.controller;

import cn.appsys.pojo.Info;
import cn.appsys.pojo.Page;
import cn.appsys.pojo.User;
import cn.appsys.service.CategoryService;
import cn.appsys.service.DictionaryService;
import cn.appsys.service.InfoService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * putway @author mj173
 */
@Controller
@RequestMapping(value = "/info")
public class InfoController {

    private final static Long STATUS_PUTAWAY = 4L;
    private final static Long STATUS_SOLDOUT = 5L;
    private final static Long STATUS_PASS = 2L;

    @Resource
    InfoService infoService;
    @Resource
    DictionaryService dictionaryService;
    @Resource
    CategoryService categoryService;

    @RequestMapping(value = "backendlist")
    public String backendlist(Model model, Info info, @RequestParam(value = "pageIndex", defaultValue = "1") Integer currentPageNo) {
        Page page = new Page();
        page.setCurrentPageNo(currentPageNo);
        info.setStatus(1L);
        setAttr(model, info, page);
        return "backend/applist";
    }

    private void setPage(Model model, Info info, Page page) {
        page.setTotalCount(infoService.getCount(info.getSoftwareName(), info.getStatus(),
                info.getFlatformId(), info.getDevId(), info.getCategoryLevel1(),
                info.getCategoryLevel2(), info.getCategoryLevel3()));
        model.addAttribute("appInfoList", infoService.getAll(info.getSoftwareName(), info.getStatus(),
                info.getFlatformId(), info.getDevId(), info.getCategoryLevel1(),
                info.getCategoryLevel2(), info.getCategoryLevel3(), page.getOffset(), page.getPageSize()));
        model.addAttribute("flatFormList", dictionaryService.getListByTypeCode("APP_FLATFORM"));
        model.addAttribute("categoryLevel1List", categoryService.getCategoryLevelList(1));
        model.addAttribute("categoryLevel2List", categoryService.getCategoryLevelList(info.getCategoryLevel1() == null ? null : info.getCategoryLevel1().intValue()));
        model.addAttribute("categoryLevel3List", categoryService.getCategoryLevelList(info.getCategoryLevel2() == null ? null : info.getCategoryLevel2().intValue()));
    }

    @RequestMapping(value = "devlist")
    public String devlist(Model model, Info info, @RequestParam(value = "pageIndex", defaultValue = "1") Integer currentPageNo) {
        Page page = new Page();
        page.setCurrentPageNo(currentPageNo);
        setAttr(model, info, page);
        model.addAttribute("statusId", info.getStatus());
        model.addAttribute("statusList", dictionaryService.getListByTypeCode("APP_STATUS"));
        return "developer/appinfolist";
    }

    private void setAttr(Model model, Info info, Page page) {
        setPage(model, info, page);
        model.addAttribute("pages", page);
        model.addAttribute("categoryLevel3", info.getCategoryLevel3());
        model.addAttribute("categoryLevel2", info.getCategoryLevel2());
        model.addAttribute("categoryLevel1", info.getCategoryLevel1());
        model.addAttribute("flatformId", info.getFlatformId());
        model.addAttribute("softwareName", info.getSoftwareName());
    }

    @GetMapping("/checkAppName")
    @ResponseBody
    public Object checkAppName(@RequestParam(value = "APKName", required = false) String apkName) {
        Info info = infoService.checkApkName(apkName);
        String str = null;
        if ("".equals(apkName)) {
            str = "empty";
        } else if (info != null) {
            str = "exist";
        } else {
            str = "noexist";
        }
        return JSON.toJSONString(str);
    }

    @RequestMapping("/infoAdd")
    public String InfoAdd(Info info, HttpServletRequest request, @RequestParam(value = "PicPath", required = false) MultipartFile multipartFile) {
        HttpSession session = request.getSession();
        String logoPicPath = null;
        String logoLocPath = null;
        if (!multipartFile.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + java.io.File.separator + "uploadfiles");
            String oldFileName = multipartFile.getOriginalFilename();  //原文件名
            String suffix = FilenameUtils.getExtension(oldFileName);   //原文件后缀
            int fileSize = 10000000;
            if (multipartFile.getSize() > fileSize) {//上传大小不得超过 50k
                request.setAttribute("fileUploadError", "* 上传文件过大！");
                return "developer/appinfoadd";
            } else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png")
                    || suffix.equalsIgnoreCase("jpeg")) {//上传图片格式
                String fileName = info.getApkName() + ".jpg";//上传LOGO图片命名:apk名称.apk
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    multipartFile.transferTo(targetFile);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    request.setAttribute("fileUploadError", "* 上传失败！");
                    return "developer/appinfoadd";
                }
                logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                logoLocPath = path + File.separator + fileName;
            } else {
                request.setAttribute("fileUploadError", "* 上传文件格式不正确！");
                return "developer/appinfoadd";
            }
        }
        info.setCreatedBy(((User) session.getAttribute("devUserSession")).getId());
        info.setCreationDate(new Date());
        info.setLogoPicPath(logoPicPath);
        info.setLogoLocPath(logoLocPath);
        info.setDevId(((User) session.getAttribute("devUserSession")).getId());
        info.setStatus(1L);
        Integer integer = infoService.addInfo(info);
        if (integer > 0) {
            return "redirect:/info/devlist";
        }
        return "redirect:/user/toAdd";
    }

    @RequestMapping("/infoUpdate")
    public String infoUpdate(Info info, @RequestParam("attach") MultipartFile attach, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String logoPicPath = null;
        String logoLocPath = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + java.io.File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();  //原文件名
            String suffix = FilenameUtils.getExtension(oldFileName);  //原文件后缀
            int fileSize = 10000000;
            if (attach.getSize() > fileSize) {//上传大小不得超过 50k
                request.setAttribute("fileUploadError", "* 上传文件过大！");
                return "developer/appinfoadd";
            } else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png")
                    || suffix.equalsIgnoreCase("jpeg")) {//上传图片格式
                String fileName = info.getApkName() + ".jpg";//上传LOGO图片命名:apk名称.apk
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                } else {
                    targetFile.delete();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    request.setAttribute("fileUploadError", "* 上传失败！");
                    return "developer/appinfoadd";
                }
                logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                logoLocPath = path + File.separator + fileName;
            } else {
                request.setAttribute("fileUploadError", "* 上传文件格式不正确！");
                return "developer/appinfoadd";
            }
        }
        info.setCreatedBy(((User) session.getAttribute("devUserSession")).getId());
        info.setCreationDate(new Date());
        info.setLogoPicPath(logoPicPath);
        info.setLogoLocPath(logoLocPath);
        info.setDevId(((User) session.getAttribute("devUserSession")).getId());
        Integer integer = infoService.updateInfo(info);
        if (integer > 0) {
            return "redirect:/info/devlist";
        }
        return "redirect:/user/toUpdate?id=" + info.getId();
    }

    @RequestMapping("/delFile")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public String delFile(@RequestParam("id") Long id,@RequestParam("logoLocPath") String logoLocPath) {
        Integer integer = null;
        String str = "failed";
        try {
            integer = infoService.updatePicBeNull(id,logoLocPath);
            if (integer > 0) {
                str = "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
            str = "failed";
        } finally {
            return JSON.toJSONString(str);
        }
    }

    @RequestMapping(value = "/sale/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public Object sale(@PathVariable("id") Long id) {
        Map<String, Object> map = new HashMap<>(10);
        Integer result = 0;
        try {
            Info infoById = infoService.getInfoById(id);
            if (infoById != null) {
                map.put("errorCode", "0");
                if (infoById.getStatus().equals(STATUS_SOLDOUT) || infoById.getStatus().equals(STATUS_PASS)) {
                    result = infoService.updateStatus(id, STATUS_PUTAWAY);
                } else if (infoById.getStatus().equals(STATUS_PUTAWAY) || infoById.getStatus().equals(STATUS_PASS)) {
                    result = infoService.updateStatus(id, STATUS_SOLDOUT);
                }
                map.put("resultMsg", result > 0 ? "success" : "failed");
            } else {
                map.put("errorCode", "param000001");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("errorCode", "exception000001");
        } finally {
            return JSON.toJSONString(map);
        }
    }


}
